package com.example.lock;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityOptionsCompat;

import com.filemanager.picture.bean.FileRelay;
import com.filemanager.picture.interfaces.OnResultListener;
import com.king.view.splitedittext.SplitEditText;

import Utils.KeybordUtil;

import static android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;

public class LockService extends Service implements View.OnClickListener {
    private WindowManager wm;
    private WindowManager.LayoutParams wmParm;
    private View rootview;
    private LinearLayout function_view;
    private LinearLayout lin_pic, lin_passward, lin_lock, lin_back;
    private BubbleLinearLayout setPwRootView;
    private LinearLayout inputPwRootView;
    private boolean isShowingSetPw;
    private test.SplitEditText setPwRootView_splitEt,inputPwRootView_splitEt;
    private LockView lockView;
    private ImageView choose_picture_imageView;
    private FrameLayout choose_picture_layout;
    private ImageButton delete_picture_imageBtn;
    private FrameLayout lockview_rootview;
    private ImageView circle1, circle2, circle3;
    private TextView pw_input_msg;
    //解锁输入密码
    private String pw = null;
    private String image_path = "";


    public static void saveActivity(MainActivity mainActivity) {
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        wmParm = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            wmParm.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            wmParm.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        wmParm.format = PixelFormat.RGBA_8888;
        wmParm.gravity = Gravity.CENTER;
        wmParm.flags = FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;// 焦点
        wmParm.width = WindowManager.LayoutParams.MATCH_PARENT;
        wmParm.height = WindowManager.LayoutParams.MATCH_PARENT;


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        rootview = LayoutInflater.from(this).inflate(R.layout.rootview, null);
        lin_pic = rootview.findViewById(R.id.lin_pic);
        lin_passward = rootview.findViewById(R.id.lin_passward);
        lin_lock = rootview.findViewById(R.id.lin_lock);
        setPwRootView = rootview.findViewById(R.id.setPwRootView);
        setPwRootView_splitEt = rootview.findViewById(R.id.spliteditext);
        function_view = rootview.findViewById(R.id.functionView);
        lockView = rootview.findViewById(R.id.lockView);
        choose_picture_imageView = rootview.findViewById(R.id.choose_picture_imageView);
        choose_picture_layout = rootview.findViewById(R.id.choose_picture_layout);
        delete_picture_imageBtn = rootview.findViewById(R.id.delete_picture_imageBtn);
        inputPwRootView = rootview.findViewById(R.id.inputLockPwLin);
        inputPwRootView_splitEt = rootview.findViewById(R.id.inputPwRootView_splitEt);
        lin_back = rootview.findViewById(R.id.back);
        lockview_rootview = rootview.findViewById(R.id.lockview_rootview);
        circle1 = rootview.findViewById(R.id.circle1);
        circle2 = rootview.findViewById(R.id.circle2);
        circle3 = rootview.findViewById(R.id.circle3);
        pw_input_msg= rootview.findViewById(R.id.pw_input_msg);
        initListener();
        wm.addView(rootview, wmParm);
        return super.onStartCommand(intent, flags, startId);
    }

    private void initListener() {
        lin_pic.setOnClickListener(this);
        lin_passward.setOnClickListener(this);
        lin_lock.setOnClickListener(this);
        lin_back.setOnClickListener(this);
        delete_picture_imageBtn.setOnClickListener(this);
        setPwRootView_splitEt.setOnTextInputListener(new test.SplitEditText.OnTextInputListener() {
            @Override
            public void onTextInputChanged(String text, int length) {
                Log.i("SQS", "调用onTextInputChanged--length" + length + "|" + text);
                if (length != 6) {
                    pw = null;
                }
            }

            @Override
            public void onTextInputCompleted(String text) {
                hideSetPwView();
                pw = text;
                Toast.makeText(GlobalApplication.context, "密码设置成功", Toast.LENGTH_SHORT).show();
            }
        });

        inputPwRootView_splitEt.setOnTextInputListener(new test.SplitEditText.OnTextInputListener() {
            @Override
            public void onTextInputChanged(String text, int length) {
                pw_input_msg.setText("输入密码:");
                pw_input_msg.setTextColor(Color.WHITE);
            }

            @Override
            public void onTextInputCompleted(String text) {
                if (text != null && text.equals(pw)) {
                    //顺利解锁
                    inputPwRootView.setVisibility(View.GONE);
                    function_view.setVisibility(View.VISIBLE);
                    rootview.setBackgroundColor(Color.TRANSPARENT);
                    setPwRootView_splitEt.setText(null);
                    inputPwRootView_splitEt.setText(null);
                    wmParm.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
                    wm.updateViewLayout(rootview, wmParm);

                } else {
                    wmParm.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN;
                    wm.updateViewLayout(rootview, wmParm);
                    inputPwRootView_splitEt.setInputBorderColor(getResources().getColor(R.color.pw_error));
                    pw_input_msg.setText("密码错误！");
                    pw_input_msg.setTextColor(getResources().getColor(R.color.pw_error));
                    Animation animation = AnimationUtils.loadAnimation(GlobalApplication.context, R.anim.translate_snake);
                    animation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            wmParm.flags =WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_FULLSCREEN;
                            wm.updateViewLayout(rootview, wmParm);
                            inputPwRootView_splitEt.setInputBorderColor(getResources().getColor(R.color.pw_normal));
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    inputPwRootView_splitEt.startAnimation(animation);


                }
            }
        });

        lockView.setOnLockListener(new LockView.OnLockSuccessListener() {
            @Override
            public void draging() {
                MyAnimation.stopAnim();
            }

            @Override
            public void fail() {
                MyAnimation.start(GlobalApplication.context, circle1, circle2, circle3);
            }

            @Override
            public void success() {
                Log.i("SQS", "UNlOCK_success!");
                lockview_rootview.setVisibility(View.GONE);
                setPwRootView.setVisibility(View.GONE);
                MyAnimation.stopAnim();


                //是否设置了密码
                if (pw != null) {
                    inputPwRootView.setVisibility(View.VISIBLE);
                    wmParm.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_FULLSCREEN;
                    wm.updateViewLayout(rootview, wmParm);
                    KeybordUtil.showSoftInput(inputPwRootView_splitEt);
                } else {
                    rootview.setBackgroundColor(Color.TRANSPARENT);
                    inputPwRootView.setVisibility(View.GONE);
                    function_view.setVisibility(View.VISIBLE);
                }

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lin_pic:
                //选择图片
//                Intent intent = new Intent();
//                intent.setType("image/*");
//                intent.setAction(Intent.ACTION_GET_CONTENT);
//                intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
//                getApplication().startActivity(intent);


//                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
//                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
//                }else {
//                    Toast.makeText(this,"您已经申请了权限!",Toast.LENGTH_SHORT).show();
//                }


                rootview.setVisibility(View.GONE);
                wm.updateViewLayout(rootview, wmParm);
                FileRelay.getInstance().setListener(onResultListener);
                //mCustomPopWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);
                ActivityOptionsCompat compat = ActivityOptionsCompat.makeCustomAnimation(this, R.anim.picture_anim_enter, 0);
                FileRelay.getInstance().startActivity(getApplication(), "", null, compat.toBundle());

                break;
            case R.id.delete_picture_imageBtn:
                //删除图片
                choose_picture_layout.setVisibility(View.GONE);
                image_path = "";
                break;
            case R.id.lin_passward:
                //设置密码
                if (isShowingSetPw) {
                    hideSetPwView();
                } else {
                    showSetPwView();
                }
                break;
            case R.id.lin_lock:
                //屏幕锁定
                lockview_rootview.setVisibility(View.VISIBLE);
                function_view.setVisibility(View.GONE);
                setPwRootView.setVisibility(View.GONE);

                if ("".equals(image_path)) {
                    rootview.setBackgroundColor(Color.parseColor("#E0303030"));
                } else {
                    rootview.setBackground(new BitmapDrawable(BitmapFactory.decodeFile(image_path)));
                }

                MyAnimation.start(GlobalApplication.context, circle1, circle2, circle3);
                break;

            case R.id.back:
                //退出
                stopSelf();
                System.exit(0);
                wm.removeView(rootview);
                break;
        }
    }


    /**
     * 图片选择监听
     */
    private OnResultListener onResultListener = new OnResultListener() {
        @Override
        public void onChooseFilePath(String path) {
            image_path = path;
            Log.i("SQS:", "PIC_PATH=" + image_path);
            choose_picture_layout.setVisibility(View.VISIBLE);
            choose_picture_imageView.setImageBitmap(BitmapFactory.decodeFile(image_path));
            rootview.setVisibility(View.VISIBLE);
            wm.updateViewLayout(rootview, wmParm);
        }

        @Override
        public void onCancel() {
            rootview.setVisibility(View.VISIBLE);
            wm.updateViewLayout(rootview, wmParm);
        }

        @Override
        public void onResume() {

        }
    };


    /**
     * 展开密码设置view
     */
    private void showSetPwView() {
        setPwRootView.setVisibility(View.VISIBLE);
        wmParm.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_FULLSCREEN;
        isShowingSetPw = !isShowingSetPw;
        wm.updateViewLayout(rootview, wmParm);
        KeybordUtil.showSoftInput(setPwRootView_splitEt);
    }

    /**
     * 隐藏密码设置view
     */
    private void hideSetPwView() {
        setPwRootView.setVisibility(View.GONE);
        wmParm.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        isShowingSetPw = !isShowingSetPw;
        wm.updateViewLayout(rootview, wmParm);
    }


}
